import { isElectron, windowMove } from "@/utils";
import { App } from "vue";

const register = (app: App<Element>) => {
  app.directive("dragWindow", {
    mounted(el: HTMLElement) {
      // 鼠标进入判断，只有鼠标进入到范围内，才能进行鼠标按压拖拽
      let enterFlag = false;
      // 鼠标按压判断，只有鼠标进入范围内，并且按压状态，此时释放鼠标才会关闭窗口移动
      let mousedownFlag = false;
      let timer: NodeJS.Timeout | null;
      if (isElectron()) {
        const { ipcRenderer } = require("electron");
        ipcRenderer.on("systemMouseUp", () => {
          if (enterFlag && mousedownFlag) {
            windowMove(false);
            mousedownFlag = false;
          }
        });
      }
      /**鼠标按压 */
      function mousedown(e) {
        if (enterFlag) {
          windowMove(true);
          mousedownFlag = true;
        }
      }

      /**鼠标释放 */
      function mouseup() {
        if (enterFlag && mousedownFlag) {
          windowMove(false);
          mousedownFlag = false;
        }
      }

      /**鼠标移入 */
      function mouseenter(e: any) {
        enterFlag = true;
      }

      /**鼠标移出 */
      function mouseleave() {
        enterFlag = false;
        // 避免卡顿的情况下，鼠标滑出移动范围，但窗口仍跟随鼠标移动
        if (timer !== null) {
          timer = setTimeout(() => {
            mousedownFlag = false;
            windowMove(false);
            timer = null;
          }, 1000);
        }
      }
      el.onmousedown = mousedown;
      el.onmouseup = mouseup;
      el.onmouseenter = mouseenter;
      el.onmouseleave = mouseleave;
    },
  });
  app.directive("notDrag", {
    mounted(el: HTMLElement) {
      /**鼠标按压 */
      function mousedown(e) {
        console.log("notdrag");

        e.stopPropagation();
      }

      /**鼠标释放 */
      function mouseup(e) {
        e.stopPropagation();
      }

      /**鼠标移入 */
      function mouseenter(e: any) {
        e.stopPropagation();
      }

      /**鼠标移出 */
      function mouseleave(e) {
        e.stopPropagation();
      }
      el.onmousedown = mousedown;
      el.onmouseup = mouseup;
      el.onmouseenter = mouseenter;
      el.onmouseleave = mouseleave;
    },
  });
};

export default register;
